<template>
  <div class="inventory">
    <el-dialog
      width="990px"
      title="选择库存"
      :visible.sync="showDialogVisible"
      custom-class="revenue-code-number"
      :before-close="beforeClose"
      v-if="ifTrue"
    >
      <div class="el-dialog__body-bodys">
        <div class="container">
          <div class="header">已选择({{ inventoryTableData2.length }}个)</div>
          <div class="ccui-multifunctional-table-wrapper">
            <el-table
              :data="inventoryTableData2"
              ref="multipleTable2"
              height="200"
              border
              :fit="true"
            >
              <el-table-column label="序号" width="45" fixed>
                <template slot-scope="scope">
                  <span>{{ scope.$index + 1 }}</span>
                </template>
              </el-table-column>
              <el-table-column
                v-for="(table, index) in tableHeadOptions"
                :fixed="table.fixed || false"
                :key="index"
                :type="table.type"
                :label="table.label"
                :min-width="table.width"
                :prop="table.prop"
                :align="table.align || 'left'"
                :header-align="table.headerAlign || 'left'"
                :filters="table.filters"
                :formatter="table.formatter"
                :show-overflow-tooltip="true"
              />
              <el-table-column label="操作" width="50px" fixed="right">
                <template slot-scope="{ row, $index }">
                  <el-button
                    size="mini"
                    type="text"
                   
                    @click="inventoryDeleteTable(row, $index)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>

        <div class="container">
          <el-search
            :formProp="formData"
            @search="search"
            @change="inventoryChange"
            @resetForm="resetForm"
            width="400px"
            placement="bottom-start"
            class="ccui-highsearch no-print"
            :selectClear="true"
          >
            <template slot="search">
              <el-input
                v-model="formData.materialName"
                clearable
                searchLabel="设备物资名称"
                placeholder="请输入设备物资名称模糊查询"
                @blur="handleTrim('materialName')"
              ></el-input>
              <el-input
                v-model="formData.materialState"
                clearable
                searchLabel="设备物资说明"
                placeholder="请输入设备物资说明模糊查询"
                @blur="handleTrim('materialState')"
              ></el-input>
              <el-input
                v-model="formData.batchNumber"
                clearable
                searchLabel="批次号"
                placeholder="请输入批次号模糊查询"
                @blur="handleTrim('batchNumber')"
              ></el-input>
              <el-date-picker
                v-model="formData.shenPiTongGuoDate"
                clearable
                searchLabel="入库时间"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
              >
              </el-date-picker>
              <el-select
                class="ccui-form-longInput"
                v-model="formData.storageType"
                searchLabel="入库类型"
                placeholder="请选择入库类型查询"
                @change="handleStorageType"
              >
                <el-option
                  v-for="item in PutInStorageState"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </template>
            <!-- 表单高级搜索 -->
            <el-input
              v-model="formData.materialName"
              clearable
              searchLabel="设备物资名称"
              placeholder="请输入设备物资名称模糊查询"
              @blur="handleTrim('materialName')"
              slot="searchItem1"
            ></el-input>
            <el-input
              v-model="formData.materialState"
              clearable
              searchLabel="设备物资说明"
              placeholder="请输入设备物资说明模糊查询"
              @blur="handleTrim('materialState')"
              slot="searchItem2"
            ></el-input>
            <el-input
              v-model="formData.batchNumber"
              clearable
              searchLabel="批次号"
              placeholder="请输入批次号模糊查询"
              @blur="handleTrim('batchNumber')"
              slot="searchItem4"
            ></el-input>
            <el-date-picker
              v-model="formData.shenPiTongGuoDate"
              clearable
              searchLabel="入库时间"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              slot="searchItem5"
            >
            </el-date-picker>
            <el-select
              class="ccui-form-longInput"
              v-model="formData.storageType"
              searchLabel="入库类型"
              placeholder="请选择入库类型查询"
              slot="searchItem6"
              @change="handleStorageType"
            >
              <el-option
                v-for="item in PutInStorageState"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
            <div searchLabel="其他费用" @change="handleIsOtherCost" class="ccui-form-longInput"  slot="searchItem7" style="display:inline-block">
              <el-radio v-model="formData.isOtherCost" label="1">是</el-radio>
              <el-radio v-model="formData.isOtherCost" label="0">否</el-radio>
            </div>
          </el-search>
          <!-- 搜索条件结束 -->
          <div class="ccui-multifunctional-table-wrapper">
            <el-table
              :data="inventoryTableDatas"
              height="200"
              @select="inventorySelectTable"
              @select-all="inventorySelectTableAll"
              ref="inventoryMultipleTable"
              border
              :fit="true"
              row-key="id"
            >
              <el-table-column width="35" type="selection"  reserve-selection/>

              <el-table-column label="序号" width="45" align="center" fixed>
                <template slot-scope="scope">
                  <span>{{ scope.$index + 1 }}</span>
                </template>
              </el-table-column>
              <el-table-column
                v-for="(table, index) in tableHeadOptions"
                :fixed="table.fixed || false"
                :key="index"
                :type="table.type"
                :label="table.label"
                :min-width="table.width"
                :prop="table.prop"
                :align="table.align || 'left'"
                :header-align="table.headerAlign || 'left'"
                :filters="table.filters"
                :formatter="table.formatter"
                :show-overflow-tooltip="true"
              />
            </el-table>
          </div>
          <div class="table-footer" style="height: 35px">
            <div id="ccui-paging">
              <el-pagination
                :total="totalNum"
                :page-size="formData.pageSize"
                :current-page="formData.pageNo"
                :page-sizes="[10,20, 50, 100, 200, 500]"
                background
                layout="total, sizes, prev, pager, next, jumper"
                popper-class="ccui-paging-page-size-popper"
                @prev-click="handlePrev"
                @next-click="handleNext"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
              <el-button
                class="ccui-pagination-btn"
                size="mini"
                type="default"
                @click="handleChangeSize('none')"
                >确定</el-button
              >
            </div>
          </div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button
          size="mini"
          type="default-mini"
          @click="handleQuxiao"
          >取 消</el-button
        >
        <el-button
          size="mini"
          type="primary-font-mini"
          @click="inventoryConfirm"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { uniqueByJson } from "@/basa/utils";
import { setSessionItem, getSessionItem } from "@/basa/utils";
import {getTableList} from "../api"
export default {
  name: "dialogMultiSelectTableTow",
  props: {
    // 数组当前行下标
    rowIndex: {
      type: Number,
      default: 0,
    },
    warehouseId:{
      type:String,
       default() {
        return "";
      }
    }
  },
  data() {
    return {
      showDialogVisible: false,
      inventoryTableDatas: [],
      inventoryTableData2: [],
      formData: {
        isOtherCost:"1",
        storageType:"1",
        warehouseId:"",
        pageNo: 1,
        pageSize: 10,
        },
      formDataSearch:{
        isOtherCost:"1",
        storageType:"1",
        warehouseId:"",
        pageNo: 1,
        pageSize: 10,
      },

      totalNum: 0,
      beforeSelectData: [],
      selectTableListTow: [], // 回显数据拷贝
      selectList: [],
      contractCode: null,
      storageType: null,
      warehouseIdId:"",//仓库id
      ifTrue:false,
      tableHeadOptions:[
        {
          label: "批次号",
          prop: "batchNumber",
          width: "200",
          checked: true,
          align: "left"
        },
        {
          label: "设备物资编码",
          prop: "materialCode",
          width: "120",
          checked: true,
          align: "left"
        },
        {
          label: "设备物资名称",
          prop: "materialName",
          width: "120",
          checked: true,
          align: "left"
        },
        {
          label: "设备物资说明",
          prop: "materialState",
          width: "150",
          checked: true,
          align: "left"
        },
        {
          label: "计量单位",
          prop: "measureUnit",
          width: "100",
          checked: true,
          align: "left"
        },
        {
          label: "入库数量",
          prop: "storageCount",
          width: "100",
          checked: true,
          align: "left"
        },
        {
          label: "库存数量",
          prop: "actualStockCount",
          width: "100",
          checked: true,
          align: "left"
        },
        {
          label: "可用库存数量",
          prop: "availableStockCount",
          width: "100",
          checked: true,
          align: "left"
        },
        {
          label: "入库时间",
          prop: "approvalAdoptTime",
          width: "150",
          checked: true,
          align: "left"
        },
        {
          label: "含税单价",
          prop: "unitPriceWithTax",
          width: "100",
          checked: true,
          align: "right",
          headerAlign:"left"
        },
        {
          label: "库存金额",
          prop: "actualStockWithTax",
          width: "100",
          checked: true,
          align: "right",
          headerAlign:"left"
        },
        {
          label: "币种",
          prop: "currencyName",
          width: "100",
          checked: true,
          align: "left"
        },
        {
          label: "供应商",
          prop: "supplierName",
          width: "150",
          checked: true,
          align: "left"
        },
        {
          label: "入库类型",
          prop: "storageTypeName",
          width: "100",
          checked: true,
          align: "left"
        }
      ],
      PutInStorageState:[
        {
          label:"暂估",
          value:"0"
        },
        {
          label:"正式",
          value:"1"
        }
      ],
    };
  },
  watch:{
    //仓库id
    warehouseId(data){
      this.formData.warehouseId = data
      this.formDataSearch.warehouseId = data
      this.warehouseIdId = data
    }
  },
  methods: {
    // 请求接口
    getTableList(data){
      getTableList(data).then((res) => {
        this.inventoryTableDatas = res.data.data.rows;
        this.inventoryTableDatas.forEach(item=>{
          if(item.storageCount){
            item.storageCount = (+item.storageCount).toFixed(3);
          }
          if(item.actualStockCount){
            item.actualStockCount = (+item.actualStockCount).toFixed(3);
          }
          if(item.availableStockCount){
            item.availableStockCount = (+item.availableStockCount).toFixed(3);
          }
          if(item.unitPriceWithTax){
            item.unitPriceWithTax = (+item.unitPriceWithTax).toFixed(2);
          }
          if(item.actualStockWithTax){
            item.actualStockWithTax = (+item.actualStockWithTax).toFixed(2);
          }
          item.storageTypeName = item.storageType === 0 ? "暂估" : "正式"
        })
        this.totalNum = res.data.data.recordsTotal;
        this.$nextTick(() => {
          this.$refs.inventoryMultipleTable.doLayout();
          this.$refs.multipleTable2.doLayout();
        });
      })
    },
    inventoryChange(index, key, value) {
      let isOtherCost =JSON.parse(JSON.stringify(this.formData.isOtherCost)) 
      let storageType =JSON.parse(JSON.stringify(this.formData.storageType)) 
      let pageNo =JSON.parse(JSON.stringify(this.formData.pageNo)) 
      let pageSize =JSON.parse(JSON.stringify(this.formData.pageSize))
      const formDataKeys = Object.keys(this.formData);
      formDataKeys.map((_) => {
        if (_ !== key) this.formData[_] = "";
      });
      this.formData.isOtherCost = isOtherCost
      this.formData.storageType = storageType
      this.formData.warehouseId = this.warehouseIdId
      this.formData.pageNo = pageNo
      this.formData.pageSize = pageSize
    },
    // 单选
    inventorySelectTable(selection, row) {
      // batchNumber  每条数据的唯一 id
      // const { batchNumber } = row;
      this.inventoryTableData2 = [...this.selectList, ...selection];
      // 去重
      this.inventoryTableData2 = uniqueByJson(
        this.inventoryTableData2,
        "batchNumber"
      );
      if (this.inventoryTableData2.length <= 0) {
        this.inventoryGetMcConcBill();
      }
      this.beforeSelectData = selection.map((n) => n.batchNumber);
    },
    // 全选
    inventorySelectTableAll(selection) {
      this.inventoryTableData2 = [...this.selectList, ...selection];
      // 去重
      this.inventoryTableData2 = uniqueByJson(
        this.inventoryTableData2,
        "batchNumber"
      );
      this.beforeSelectData = selection.map((n) => n.batchNumber);
    },
    // 删除
    inventoryDeleteTable(row, index) {
      this.inventoryTableData2 = this.inventoryTableData2.filter(
        (item) => item.batchNumber !== row.batchNumber
      );
      this.$refs.inventoryMultipleTable.toggleRowSelection(row, false);
    },
    inventoryConfirm() {
      let newArr = [
        {zhengshi:1},
        {zangu:1}
      ]
      this.inventoryTableData2.forEach(item=>{
       if(item.storageType === 0){
          newArr[1].zangu = 2
        }
        if(item.storageType === 1){
          newArr[0].zhengshi = 2
        }
      })
      if(this.inventoryTableData2.length){
        if(newArr[0].zhengshi !== newArr[1].zangu){
          this.showDialogVisible = false;
          this.$emit("confirm", this.inventoryTableData2);
          this.resetParams();
        }else{
          this.$message.warning("请选择相同入库类型的物资进行出库！");
        }
      }else{
        this.$message.warning("请选择物资进行出库！");
      }
    },
    handleStorageType(){
      this.$forceUpdate()//强制刷新
    },
    handleIsOtherCost(){
      this.$forceUpdate()//强制刷新
    },
    //取消
    handleQuxiao(){
      this.showDialogVisible = false;
      this.resetParams()
    },
    //点击x
    beforeClose(){
     this.handleQuxiao()
    },
    // 重置表单inventoryReset
    resetForm() {
      let pageNo =JSON.parse(JSON.stringify(this.formDataSearch.pageNo)) 
      let pageSize =JSON.parse(JSON.stringify(this.formDataSearch.pageSize))
      this.formData.isOtherCost = "1" 
      this.formData.storageType = "1"
      this.formData.pageNo = pageNo 
      this.formData.pageSize = pageSize
      this.formData.warehouseId = this.warehouseIdId
    },
    resetParams() {
      this.formData = {};
      this.formData.warehouseId = this.warehouseIdId
      this.formData.isOtherCost = "1"
      this.formData.storageType = "1"
      this.formData.pageNo = 1;
      this.formData.isShowPageLoading = true;
      this.formData.pageSize = 10;
      this.inventoryTableDatas = [];
      this.inventoryTableData2 = [];
      this.$refs.inventoryMultipleTable.clearSelection();//清理选择框
      this.ifTrue = false
    },

    // 搜索相关
    //去空格
    handleTrim(key) {
      if(this.formData[key]){
        this.$set(
          this.formData,
          key,
          this.formData[key].replace(/(^\s*)|(\s*)$/g, "")
        )
      }
    },
    // 上一页
    handlePrev() {},
    // 下一页
    handleNext() {},
    //  显示条数更改
    handleSizeChange(val) {
      this.formDataSearch.pageNo = 1;
      this.formDataSearch.pageSize = val;
      this.formData.pageNo = 1;
      this.formData.pageSize = val;
      setSessionItem("pageSize", this.tableName, val);
      this.getTableList(this.formDataSearch);
    },
    //翻页确定
    handleChangeSize() {
      this.getTableList();
    },
    // 当前页码更改
    handleCurrentChange(val) {
      // 跳转翻页都会调这个方法
      this.formDataSearch.pageNo = val;
      this.getTableList(this.formDataSearch);
    },
    // 分页 end
    // 高级搜索所需函数 start
    // 高级搜索展开按钮
    search(searchData) {
      const isOtherCostSelect = this.formData.isOtherCost
      const storageType = this.formData.storageType
      const pageSize = this.formData.pageSize
      this.formDataSearch = JSON.parse(JSON.stringify(searchData));
      if(this.formDataSearch.shenPiTongGuoDate){
        this.formDataSearch.approvalAdoptStartDate = this.formDataSearch.shenPiTongGuoDate[0]
        this.formDataSearch.approvalAdoptEndDate = this.formDataSearch.shenPiTongGuoDate[1]
      }
      this.formDataSearch.warehouseId = this.warehouseIdId
      this.formDataSearch.isOtherCost = isOtherCostSelect
      this.formDataSearch.storageType = storageType     

      this.formDataSearch.reportOrgId = getSessionItem("userInfo", "orgId");
      this.formDataSearch.pageNo = 1;
      this.formDataSearch.isShowPageLoading = true;
      this.formDataSearch.pageSize = pageSize;
      this.getTableList(this.formDataSearch);
    }
    // 高级搜索 end
  },
};
</script>

<style lang="scss" scoped>
.inventory {
  display: inline-block;
  & + .inventory {
    margin-left: 10px;
  }
  /deep/ .el-dialog__header {
    // display: flex;
    // align-items: center;
  }
  /deep/ .el-dialog__title {
    display: inline-block;
    height: 20px;
    line-height: 20px !important;
  }
  /deep/ .revenue-code-number {
    .el-dialog__body {
      width: auto;
      height: auto;
      .ccui-form {
        margin-top: 5px;
      }
    }
  }
  /deep/ .revenue-code-number .el-dialog__body .el-dialog__body-bodys {
    .bodys-right {
      padding: 0;
      width: 400px;
    }
  }
  /deep/.el-search .el-searchs {
    float: none !important;
  }
  /deep/.el-searchs-box {
    // width: auto !important;
    margin: 0 auto;
  }
  .container {
    border: 1px solid #f1f1f1;
    padding: 10px 20px;
    .header {
      margin-bottom: 10px;
    }
    .table-footer {
      padding: 10px 0;
    }
    .ccui-statistics-card {
      padding: 0;
    }
  }
  /deep/.el-button--text {
    font-size: 13px;
  }
  // /deep/.el-input {
  //   width: 192px;
  // }
  .search-btn {
    text-align: center;
    padding: 0 0 20px 0;
  }
  // 搜索条件 启动
  /deep/ .el-form.el-searchs-bottom-form {
    .el-row {
      width: 100%;
    }
    .el-date-editor {
      width: 192px;
      .el-range-input {
        width: 50%;
      }
      .el-range-separator {
        padding: 0 10px 0 5px;
        font-size: 13px;
      }
      .el-range__close-icon,
      .el-range__icon {
        display: none;
      }
    }
  }
  /deep/ .el-dialog__body .el-form .el-form-item:last-child {
    margin-bottom: 16px;
  }
  // 搜索条件 结束
  /deep/ .ccui-multifunctional-table-wrapper .el-table {
    .el-table__body-wrapper {
      z-index: 2;
    }
    td,
    th.is-leaf {
      border-right: 1px solid #edf2fc;
    }
    // 固定行的高
    .el-table__fixed {
      height: 100% !important;
    }
    td.is-hidden > *,
    th.is-hidden > * {
      visibility: inherit;
    }
  }
}

/deep/ .el-table {
  /deep/ th {
    padding: 0;
    height: 36px;
    line-height: 36px;
  }

  .el-table__body {
    .cell {
      height: 36px;
      line-height: 36px;
    }
    border-bottom: 1px solid #edf2fc;
     border-right: 1px solid #edf2fc;
  }

}
</style>
